package cn.com.qtgl.sso.oidc.comp.tools;

import cn.com.qtgl.apis.builtin.comp.proxy.BuiltinProxy;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class AuthenticationToolUtils {

    @Resource
    private BuiltinProxy builtin;

    @Value("${system.config.default-tenant:cloud.ketanyun.cn}")
    private String defaultTenant;

    private String defaultNamespace="default";

    public String getTenant(){
        if(RequestContextHolder.currentRequestAttributes() instanceof ServletRequestAttributes servletRequestAttributes){
            HttpServletRequest request=servletRequestAttributes.getRequest();
            return getTenant(request);
        }
        return defaultTenant;
    }
    public String getTenant(HttpServletRequest request){
        String tenant=request.getParameter("tenant");
        if(StringUtils.isBlank(tenant)){
            tenant=request.getHeader("X-Tenant-ID");
        }
        if(StringUtils.isNotBlank(tenant)){
            return tenant;
        }
        return defaultTenant;
    }

    public String getNamespaces(){
        if(RequestContextHolder.currentRequestAttributes() instanceof ServletRequestAttributes servletRequestAttributes){
            HttpServletRequest request=servletRequestAttributes.getRequest();
            return getNamespace(request);
        }
        return defaultNamespace;
    }

    public String getNamespace(HttpServletRequest request){
        String namespace=request.getParameter("namespace");
        if(StringUtils.isBlank(namespace)){
            namespace=request.getHeader("X-Worker-Namespace-LIST");
        }

        if(StringUtils.isNotBlank(namespace)){
            return namespace;
        }
        return namespace;
    }

}
